package com.example.config;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.io.IoUtil;
import com.example.support.OssResult;
import com.example.support.OssTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * <h1>本地文件存储工具类</h1>
 * Created by hanqf on 2021/7/25 10:23.
 */


public class LocalOssTemplate implements OssTemplate {




    /**
     * 上传文件
     *
     * @param inputStream
     * @param fileType
     * @param fileName 可以是文件路径
     * @return
     */
    @Override
    public OssResult putFile(InputStream inputStream, String fileType, String fileName) {
        FastByteArrayOutputStream fastByteArrayOutputStream;
        try {
            Path path = Paths.get(LocalOssConfig.LOCAL_FILE_PATH + fileName);
            if (Files.notExists(path.getParent())) {
                Files.createDirectories(path.getParent());
            }
            fastByteArrayOutputStream = IoUtil.read(inputStream);
            Files.write(path, fastByteArrayOutputStream.toByteArray());
            return new OssResult(true, fileName, getOssUrl(fileName), "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return new OssResult(false, null, null, "上传文件出现异常：" + e.getMessage());
        }

    }

    @Override
    public String getOssUrl(String fileName) {
        return LocalOssConfig.DOWN_FILE_PREFIX + fileName;
    }

    @Override
    public boolean downloadFile(String fileName, String localFileName) {
        try {
            Path fromFile = Paths.get(LocalOssConfig.LOCAL_FILE_PATH + fileName);
            Path toFile = Paths.get(localFileName);

            //如果源文件存在，但是目标文件路径不存在，则先创建目标文件路径
            if (Files.exists(fromFile) && Files.notExists(toFile.getParent())) {
                Files.createDirectories(toFile.getParent());
            }
            Files.copy(fromFile, toFile);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public InputStream getInputStream(String fileName) {
        try {
            InputStream inputStream = Files.newInputStream(Paths.get(LocalOssConfig.LOCAL_FILE_PATH + fileName));
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public byte[] getBytes(String fileName) {
        try {
            return Files.readAllBytes(Paths.get(LocalOssConfig.LOCAL_FILE_PATH + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean deleteFile(String fileName) {
        try {
            Files.delete(Paths.get(LocalOssConfig.LOCAL_FILE_PATH + fileName));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
